<template>
  <div class="configDetail">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="clickLeft"
      class="nav-bar"
    >
    </van-nav-bar>
    <div class="checkAssign">
      <van-row type="flex">
        <!--  分样类型 -->
        <van-col span="12">
          <van-field
            v-model="checkType"
            name="checkType"
            label="检验类型"
            input-align="center"
            left-icon="scan"
            @click-left-icon="openScan()"
            class="deviceStyle"
          >
            <template #input>
              <fixed-select
                v-model="checkType"
                :dataList="checkTypeArr"
                @fSelect="select"
              />
            </template>
          </van-field>
        </van-col>
        <!-- 分样树 -->
        <van-col span="12">
          <van-field
            readonly
            clickable
            label="来料信息"
            v-model="sampleName"
            placeholder="请选择"
            input-align="center"
            @click="showSamplePicker = true"
          />
        </van-col>
        <!-- 班组 -->
        <van-col span="12">
          <van-field
            name="team"
            v-model="team"
            label="班组"
            input-align="center"
            @click="showPicker = true"
          >
          </van-field>
          <van-popup v-model="showPicker" round position="bottom">
            <van-picker
              show-toolbar
              value-key="Name"
              :columns="TeamList"
              @cancel="showPicker = false"
              @confirm="onConfirm"
            />
          </van-popup>
        </van-col>
        <!-- 数量 -->
        <van-col span="12">
          <van-field v-model="total" name="total" label="数量" readonly>
          </van-field>
        </van-col>
        <!-- 接受人 -->
        <van-col span="12">
          <van-field
            v-model="sampleUserName"
            input-align="center"
            name="sampleUserName"
            label="接收人"
            readonly
          >
          </van-field>
        </van-col>
        <!-- 接受时间 -->
        <van-col span="12">
          <van-field
            v-model="sampleDate"
            name="sampleDate"
            label="接收时间"
            readonly
          >
          </van-field>
        </van-col>
        <!-- 暂存位置 -->
        <van-col span="12">
          <van-field
            required
            input-align="center"
            v-model="place"
            label="暂存位置"
            placeholder=""
            clickable
            @click="seat = true"
          />
          <van-popup v-model="seat" round position="bottom">
            <van-picker
              show-toolbar
              :columns="SeatList"
              @cancel="seat = false"
              @confirm="seatBtn"
            />
          </van-popup>
        </van-col>
        <!--储存环境-->
        <van-col span="12">
          <van-field
            required
            input-align="center"
            v-model="vibe"
            label="储存环境"
            placeholder=""
            @click="vibeShow = true"
          />
          <van-popup v-model="vibeShow" round position="bottom">
            <van-picker
              show-toolbar
              :columns="vibeList"
              @cancel="seat = false"
              @confirm="videBtn"
            />
          </van-popup>
        </van-col>
      </van-row>
      <div class="content">
        <van-checkbox-group v-model="chooseArr" ref="checkboxGroup">
          <van-list
            :immediate-check="false"
            :offset="1"
            :finished="finished"
            finished-text="暂无数据"
          >
            <van-swipe-cell
              v-for="(v, i) in List"
              :key="i"
              ref="swipecell"
              type="flex"
            >
              <van-checkbox
                :name="v.attributeCode"
                shape="square"
                style="float: left; margin: 20px 0 0 10px"
              ></van-checkbox>
              <van-cell
                :title="v.attributeName"
                title-class="custom-title"
                value-class="custom-value"
                label-class="custom-label"
                style="width: 95%"
              >
                <template #label>
                  <div style="display: flex; height: 50px; align-items: center">
                    检验员：
                    <van-field
                      v-model="v.testUserName"
                      name="testUserName"
                      readonly
                      placeholder="请选择"
                      input-align="center"
                      style="
                        height: 50px;
                        width: 240px;
                        box-sizing: border-box;
                        padding: 0;
                        margin-right: 10px;
                      "
                      @click="chooseCheckPerson(v.iautoid)"
                    ></van-field>
                  </div>
                  <div>检验标准：{{ v.attributeStandard }}</div>
                </template>
              </van-cell>
              <template #right>
                <van-button
                  square
                  block
                  type="danger"
                  text="删除"
                  :style="{ height: '100%' }"
                  @click="recallItem(v.iautoid)"
                />
              </template>
            </van-swipe-cell>
          </van-list>
        </van-checkbox-group>
      </div>
    </div>
    <div class="footer">
      <van-checkbox
        v-model="checked"
        shape="square"
        @click="toggleAll"
        style="width: 200px; margin-left: 20px; font-size: 20px"
        >全选</van-checkbox
      >
      <van-field
        v-model="userName"
        name="userName"
        readonly
        placeholder="请选择"
        input-align="center"
        label="检验员："
        style="
          height: 80%;
          width: 400px;
          box-sizing: border-box;
          padding: 0;
          line-height: 50px;
          margin-right: 10px;
        "
        @click="chooseCheckPerson('out')"
      ></van-field>
      <van-button
        type="info"
        size="small"
        style="padding: 0 20px"
        @click="changeShareUser()"
        >分配</van-button
      >
      <!-- <van-button
        type="info"
        size="small"
        style="padding: 0 20px"
        @click="changeChooseUser()"
        >修改</van-button
      > -->
      <van-button
        v-if="stateShow"
        type="info"
        size="small"
        style="padding: 0 20px; position: absolute; right: 10px"
        @click="showItem()"
        >保存</van-button
      >
      <van-button
        v-else
        type="info"
        size="small"
        style="padding: 0 20px; position: absolute; right: 10px"
        @click="saveItem()"
        >保存</van-button
      >
    </div>
    <van-popup
      v-model="showSamplePicker"
      position="bottom"
      :style="{ height: '50%' }"
      :lock-scroll="false"
    >
      <van-cascader
        v-model="sampleValue"
        :options="sampleArr"
        @close="showSamplePicker = false"
        @finish="onSampleFinish"
        :field-names="sampleNames"
      />
    </van-popup>
    <van-popup v-model="showPickerUser" round position="bottom">
      <van-picker
        show-toolbar
        :columns="userList"
        @cancel="showPickerUser = false"
        @confirm="onConfirmUser"
      />
    </van-popup>
    <div class="scan" v-if="scanShow">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer>
        <button @click="closeModel">退出</button>
      </footer>
    </div>
  </div>
</template>
<script>
import { to } from "@/utils";
import FixedSelect from "@/components/FixedSelect";

import { GetTestShareTreeByCode } from "@/api/base";
import {
  GetTestShareTree,
  getUnAllocationBatchIdSelect,
  GetClassSelectByTestID,
  saveTestSampleInfo,
  getTestSampleInfo, //检验项目
  getUnAllocationTestAttributes, //检验List
  getClassUserSelect,
  GetAllocationMember,
  GetDictionarySelect,
  callBackTestAttributes,
  saveTestAttributes, //保存
} from "@/api/check";
import {
  NavBar,
  Tabbar,
  Row,
  Col,
  Field,
  Popup,
  Cascader,
  Checkbox,
  Button,
  Picker,
  List,
  Cell,
  CheckboxGroup,
  SwipeCell,
  Notify,
  Dialog,
  Toast,
} from "vant";
let scan = null;
export default {
  name: "checkAssign",
  components: {
    FixedSelect,
    [Picker.name]: Picker,
    [NavBar.name]: NavBar,
    [Tabbar.name]: Tabbar,
    [Row.name]: Row,
    [Col.name]: Col,
    [Cell.name]: Cell,
    [Field.name]: Field,
    [Popup.name]: Popup,
    [Cascader.name]: Cascader,
    [Checkbox.name]: Checkbox,
    [SwipeCell.name]: SwipeCell,
    [Button.name]: Button,
    [List.name]: List,
    [CheckboxGroup.name]: CheckboxGroup,
    [Notify.name]: Notify,
    [Dialog.name]: Dialog,
    [Toast.name]: Toast,
  },
  props: {},
  data() {
    return {
      token: "",
      checkType: "1",
      checkTypeArr: [
        { value: 1, text: "样品检验" },
        { value: 2, text: "稳定性检验" },
      ],

      sampleName: "",
      showSamplePicker: false,
      sampleNames: {
        text: "name",
        value: "code",
      },
      isOut: false,
      sampleArr: [],
      sampleValue: "",
      total: "", //数量
      sampleUserName: "", //user
      sampleDate: "", //time
      place: "", //place
      vibe: "", //vibe
      userName: "", //检验员：
      value: "",
      team: "",
      teamCode: "",
      showPicker: false,
      showPickerUser: false,
      TeamList: [],
      finished: false,
      List: [],
      chooseArr: [],
      checked: false,
      stateShow: true,
      userList: [],
      singleIautoid: "",
      testUserName: "",
      TestID: "",
      seat: false,
      SeatList: [], //暂存位置
      vibeShow: false,
      vibeList: [],
      iautoid: "",
      materialCode: "",
      scanShow: false,
      scanType: "",
      scanObj: {},
      timer: null,
      treeNode: "",
    };
  },
  computed: {},
  watch: {
    checkType(val) {
      if (val) {
        this.getTestShareTreeAxios();
      }
    },
  },
  methods: {
    seatBtn(value) {
      this.place = value.text;
      this.seat = false;
    },
    videBtn(value) {
      this.vibe = value.text;
      this.vibeShow = false;
    },
    GetSelect(value) {
      var result = {
        pageModel: { Token: this.token, Search: [value] },
      };
      GetDictionarySelect(result).then((res) => {
        if (value == "StagingPosition") {
          this.SeatList = res.Result;
        } else {
          this.vibeList = res.Result;
        }
      });
    },
    // 确定领用
    showItem() {
      if (this.place == "") {
        Toast("提示：请输入检品暂存位置");
        return;
      }
      if (this.vibe == "") {
        Toast("提示：请输入储存环境");
        return;
      }
      if (this.chooseArr.length <= 0) {
        Toast("提示:没有可分配的任务,请先选择");
        return;
      }
      var params = {
        iautoid: this.iautoid,
        Token: this.token,
        StagingPosition: this.place,
        StorageEnvironment: this.vibe,
      };

      let materialCodeList = [];
      this.List.forEach((item, index) => {
        let materialCodeString = {
          attributeCode: item.attributeCode,
          materialCode: this.materialCode,
          testID: item.testID,
          userID: item.testUserId,
        };
        materialCodeList.push(materialCodeString);
      });

      var data = {
        Token: this.token,
        attributes: materialCodeList,
        materialCode: this.materialCode,
        number: "30",
        testID: this.TestID,
      };

      saveTestSampleInfo(params).then((Res) => {
        saveTestAttributes(data).then((res) => {
          this.List = [];
          this.place = "";
          this.vibe = "";
          this.total = "";
          this.team = "";
          this.sampleDate = "";
          this.sampleUserName = "";
          this.sampleName = "";
          this.sampleValue = "";
          this.getUnAllocationList();
        });
      });
    },
    // 检验员列表
    async getClassUserList() {
      var params = { pageModel: { Token: this.token } };
      const [err, res] = await to(getClassUserSelect(params));
      var result = res.Result;

      if (!result || result.length == 0) return;
      this.userList = result;
    },
    // 修改
    changeChooseUser() {
      if (this.chooseArr.length == 0) {
        Notify({ type: "danger", message: "请勾选项目" });
        return false;
      }
      let CodeList = [];
      this.List.forEach((item) => {
        CodeList.push(item.attributeCode);
      });
      let params = {
        Token: this.token,
        TestID: this.TestID,
        ClassCode: this.teamCode,
        AttributeCode: CodeList,
      };
      GetAllocationMember(params).then((res) => {
        let el = res.Result;
        this.List.forEach((item, index) => {
          el.forEach((i, n) => {
            if (i.AttributeCode == item.attributeCode) {
              item.testUserName = i.MemberName;
              item.testUserId = i.Member.join(",");
            }
          });
        });
      });
    },
    changeShareUser() {
      if (this.chooseArr.length == 0) {
        Notify({ type: "danger", message: "请勾选项目" });
        return false;
      }
      this.List.forEach((item, index) => {
        this.chooseArr.forEach((i, n) => {
          if (item.attributeCode == i) {
            item.testUserName = this.userName;
            item.testUserId = this.userCode;
          }
        });
        //  this.userCode = value.value;
        // this.userName = value.text;
      });
    },
    recallItem(id) {
      Dialog.confirm({
        message: "确定删除吗？",
      })
        .then(() => {
          this.callBack(id);
        })
        .catch(() => {
          instance.close();
        });
    },
    callBack(id) {
      var params = {
        Token: this.token,
        iautoids: [id],
      };

      callBackTestAttributes(params)
        .then((response) => {
          Notify({ type: "success", message: response.ErrorMsg });
          this.getUnAllocationList();
        })
        .catch(() => {});
    },
    chooseCheckPerson(type) {
      if (type == "out") {
        this.isOut = true;
      } else {
        this.isOut = false;
        this.singleIautoid = type;
      }
      this.showPickerUser = true;
    },
    // 选择班组
    onConfirm(value) {
      this.team = value.Name;
      this.value = value;
      this.showPicker = false;
    },
    // 联系人
    onConfirmUser(value) {
      if (this.isOut) {
        this.userCode = value.value;
        this.userName = value.text;
        this.showPickerUser = false;
      } else {
        // 寻找列表toid匹配赋值
        for (var i = 0; i < this.List.length; i++) {
          var el = this.List[i];
          if (this.singleIautoid == el.iautoid) {
            el.testUserName = value.text;
            el.testUserId = value.value;
            this.showPickerUser = false;
            return;
          }
        }
      }
    },
    clickLeft() {
      if (scan && scan != "") {
        scan.close();
      }
      this.$router.replace({ name: "home" });
    },
    // 分样信息发生变化刷新树结构
    select(val) {
      if (val) {
        this.getTestShareTreeAxios();
      }
    },
    //是否全选
    toggleAll() {
      if (this.checked) {
        this.$refs.checkboxGroup.toggleAll(true);
      } else {
        this.$refs.checkboxGroup.toggleAll(false);
      }
    },
    // 分样选择后获取班组信息
    onSampleFinish(val) {
      this.showSamplePicker = false;
      var len = val.selectedOptions.length;
      var toDetail = val.selectedOptions[len - 1];
      this.sampleName = toDetail.name;
      this.TestID = toDetail.code;

      var params = {
        Token: this.token,
        Search: val.value,
      };
      GetClassSelectByTestID(params).then((res) => {
        this.TeamList = res.Result;
        this.team = res.Result[0].Name;
        this.teamCode = res.Result[0].Code;
        this.getSampleInfo(val.value);
        this.getUnAllocationList(val.value);
        this.sampleUserName = localStorage.getItem("username");
      });
    },
    //检验项目
    getSampleInfo(e) {
      var params = {
        Token: this.token,
        Search: [e, this.teamCode],
      };
      getTestSampleInfo(params).then((res) => {
        this.total = res.Result[0].weightTotalOne + res.Result[0].weightUnitOne;
        this.sampleDate = res.Result[0].sampleDate;
        this.iautoid = res.Result[0].iautoid;
        this.materialCode = res.Result[0].materialCode;
      });
    },
    //检验项目liebList
    getUnAllocationList(e) {
      var params = {
        Token: this.token,
        Search: [this.TestID, this.teamCode],
      };
      getUnAllocationTestAttributes(params).then((res) => {
        this.List = res.Result;
      });
    },
    // 分样树结构
    getTestShareTreeAxios() {
      this.sampleArr = [];
      var params = {
        pageModel: {
          Search: [""],
          Type: this.checkType,
          Token: this.token,
        },
      };
      getUnAllocationBatchIdSelect(params)
        .then((response) => {
          this.sampleArr = response.Result;
        })
        .catch(() => {});
    },
    openScan() {
      var that = this;
      this.scanShow = true;
      this.timer = setTimeout(that.startRecognize, 500);
    },
    startRecognize() {
      var that = this;
      this.timer = null;
      if (!window.plus) return;
      scan = new plus.barcode.Barcode("bcid");
      scan.onmarked = onmarked;
      scan.start();
      function onmarked(type, result, file) {
        switch (type) {
          case plus.barcode.QR:
            type = "QR";
            break;
          case plus.barcode.EAN13:
            type = "EAN13";
            break;
          case plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }

        scan.close();
        that.scanShow = false;
        console.log(result);
        that.getScanType(JSON.parse(result).testID, JSON.parse(result));
      }
    },
    closeModel() {
      this.scanShow = false;
      if (!window.plus) return;
      scan.close();
    },
    async getScanType(id, val) {
      var params = {
        TestId: id,
        Token: this.token,
      };
      const [err, res] = await to(GetTestShareTreeByCode(params));
      this.treeNode = res.Result;
      this.sampleName = this.treeNode.name;
      this.TestID = this.treeNode.code;

      var params = {
        Token: this.token,
        Search: val.materialCode,
      };
      GetClassSelectByTestID(params).then((res) => {
        this.TeamList = res.Result;
        this.team = res.Result[0].Name;
        this.teamCode = res.Result[0].Code;
        this.getSampleInfo(val.materialCode);
        this.getUnAllocationList(val.materialCode);
        this.sampleUserName = localStorage.getItem("username");
      });
    },
  },
  created() {
    this.token = localStorage.getItem("tokenKey");
  },
  mounted() {
    this.getTestShareTreeAxios(); //获取分样树
    this.getClassUserList();
    this.GetSelect("StagingPosition");
    this.GetSelect("StorageEnvironment");
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
};
</script>
<style scoped lang="less">
footer .van-field__label {
  font-size: 0.36rem;
  width: 4em;
}
.van-button {
  margin: 0 5px;
}
.footer .van-cell::after {
  border: none;
}
.footer input[name="userName"] {
  width: 11em;
  /* border: 1px solid #ebedf0; */
  height: 30px;
}
.configDetail {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow-y: hidden;
  // color: #fff;
}
.checkAssign {
  height: calc(100% - 2rem);
  overflow: auto;
}
.handleContent {
  width: 100%;
}
.van-col-style {
  font-size: 0.36rem;
  color: #000;
  text-align: left;
  padding-left: 0.2rem;
  margin-top: 0.2rem;
}
.content {
  padding-bottom: 30px;
}
.footer {
  width: 100%;
  position: fixed;
  bottom: 0;
  height: 1rem;
  font-size: 18px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;
  background: #fff;
  z-index: 99;
  border-top: 1px solid #ccc;
  /deep/.van-field__body {
    border: none;
  }
  /deep/.van-cell__value {
    border: 1px solid #ddd;
  }
}

/deep/input[name="total"] {
  background: #ddd;
  text-align: center;
}
/deep/input[name="sampleUserName"] {
  background: #ddd;
  text-align: center;
}
/deep/input[name="sampleDate"] {
  background: #ddd;
  text-align: center;
}
/deep/input[name="stateName"] {
  background: #ddd;
  text-align: center;
}
/deep/.van-checkbox__icon {
  font-size: 16px;
}
/deep/.van-button--small {
  height: 0.7rem;
}
.readonly /deep/.van-field__body {
  background: #ddd;
}
/deep/.van-cell {
  padding: 0.2rem 0.4rem;
}
/deep/.van-field__body {
  border-radius: 2px !important;
  border: 1px solid #ddd;
}

/deep/.van-cell {
  font-size: 0.32rem;
}
.deviceStyle /deep/.van-cell__title {
  width: 4.6em;
}
.scan {
  z-index: 999;
  height: 100%;
  width: 100%;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;

  #bcid {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 1rem;
    text-align: center;
    color: #fff;
    background: #ccc;
    font-size: 20px;
    z-index: 999;
    .closeModel {
      position: absolute;
      top: 20px;
      right: 20px;
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    bottom: 0;
    height: 1rem;
    font-size: 20px;
    button {
      height: 100%;
      width: 100%;
      border: none;
    }
  }
}
/deep/.van-cascader__header {
  height: 1rem;
}
/deep/.van-cascader__tabs.van-tabs--line .van-tabs__wrap {
  height: 1rem;
}
</style>
